<%@ include file="/WEB-INF/pages/taglibs.jsp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	
	<title>报表调度</title>
    <meta name="_csrf" content="${_csrf.token}"/>
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link href="${base}/css/antd/antd.css" rel="stylesheet" type="text/css" />
    <link href="${base}/css/stylesheets.css" rel="stylesheet" type="text/css" />
    <link href="${base}/css/datatables/datatables.css" rel="stylesheet" type="text/css" />
    <link href="${base}/css/cybertron/stylesheet.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript" src="${base}/js/react/react.js"></script>
    <script type="text/javascript" src="${base}/js/react/react-dom.js"></script>
    <script type="text/javascript" src="${base}/js/antd/antd.js"></script>

    <script type='text/javascript' src='${base}/js/jquery/jquery.min.js'></script>
    <script type='text/javascript' src='${base}/js/jquery/jquery-ui.min.js'></script>
    <script type='text/javascript' src='${base}/js/jquery/jquery-migrate.min.js'></script>
    <script type='text/javascript' src='${base}/js/jquery/globalize.js'></script>
    <script type='text/javascript' src="${base}/js/bootstrap/bootstrap.min.js"></script>

    <script type="text/javascript" src="${base}/js/plugins/mousewheel/jquery.mousewheel.min.js" ></script>
    <script type='text/javascript' src='${base}/js/plugins/mcustomscrollbar/jquery.mCustomScrollbar.min.js'></script>

    <script type="text/javascript" src="${base}/js/plugins/datatables/datatables.min.js"></script>
	
    <script type="text/javascript" src="${base}/js/cybertron/core.js"></script>
<style type="text/css">
body {
	padding: 0px;
}
.btn.check-all {
    padding: 6px;
    border-radius: 3px;
}
.btn.check-all.active:before {
    font-family: FontAwesome;
    content: "\f00c";
    position: absolute;
    top: -2px;
    left: 0;
}

#files {
  position:absolute;
  padding:8px;
  margin:10px 0 1em;
  background:#585755;
  display: none;
  width: 350px;
  border: 1px solid #666;
  border-radius: 5px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  z-index: 1000;
  top: 0;
  left: 0;
  background:-webkit-gradient(linear, 0 0, 0 100%, from(#585755), to(#333));
  background:-moz-linear-gradient(#585755, #333);
  background:-o-linear-gradient(#585755, #333);
  background:linear-gradient(#585755, #333);
  -pie-background:linear-gradient(#585755, #333);
  filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr=#585755 , endColorStr=#333);
  -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(startColorStr=#585755 , endColorStr=#333)";
  -webkit-box-shadow: #cfcfcf 0px 2px 8px;
  -moz-box-shadow: #cfcfcf 0px 2px 8px;
  box-shadow: #cfcfcf 0px 2px 8px;
}

#files>b {
  content:"";
  display:block; /* reduce the damage in FF3.0 */
  position:absolute;
  top:-10px;
  right: 5px;
  width:0;
  height: 0;
  border-width:0 10px 10px;
  border-style:solid;
  border-color:#666 transparent;
}

#files h3 {
  height: 20px;
  line-height: 20px;
  font-size: 12px;
}

#files ul.info { margin:3px 0; }
#files ul.info li { display:block; float:left; height:1.5em; font-size:20px; margin:0 2px; padding:0 3px; opacity:1; filter:none; border-left:1px solid #fff; }
#files ul.info li label {display:block;height:1.25em;line-height:1.25em;}

#files ul li { height: 22px; margin: 1px 0; opacity:0.4; filter:alpha(opacity=40); }
#files ul li input[type=radio]{ display: table-cell; width: 13px; height: 20px; margin: 0 10px; }
#files ul li.active { opacity:1; filter:none; }
#files span.error {
    color: #e87d86;
}
.ant-calendar-range-picker-input{
	padding:0;
	display: table-cell;
	color: #000;
}
.ant-calendar-input{
	color: #000 !important;	
}
</style>
</head>

<body>
<div id="content-container" class="container">
	<div class="row" id="scheduling-load-progress" style="display: none;">
		<div class="col-md-12">
			<div class="progress">
			  <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
			    <span class="sr-only">0% Complete</span>
			  </div>
			</div>
		</div>
	</div>
	
	<div class="row">
	
	    <div class="col-md-4">
            <div class="btn-group">
		    	<a id="btn-add-scheduling" class="btn btn-primary btn-sm" role="button" tabindex="0" data-trigger="focus">
					<i class="fa fa-plus-circle"></i>
			        <fmt:message key="button.add" />
				</a>
		      	<a id="btn-del-scheduling" class="btn btn-primary btn-sm" disabled="disabled">
			      	<i class="fa fa-trash"></i>
			      	<fmt:message key="button.delete" />
		      	</a>
	      	</div>
	    </div>
      	<div class="pull-right col-md-4">
      		<!--  
      		<div class="input-group">
                <input type="text" class="form-control" placeholder="" id="input-search">
                <span class="input-group-btn">
                    <button class="btn btn-default" type="button" id="btn-search">
                        <span class="fa fa-search" aria-hidden="true"></span>
                    </button>
                </span>
            </div>
            -->
      	</div>
    
	    <div class="col-md-12">
	      <table id="scheduleTable" class="table table-striped" cellspacing="0" style="width: 100%;">
	        <thead>
				<tr>
		          <th> 
					<div class="btn-group" data-toggle="buttons">
		                <label class="btn btn-xs btn-default btn-clean check-all"><input type="checkbox" id="check-all" autocomplete="off" /></label>
		            </div>
				  </th>
		          <th>状态</th>
		          <th>策略</th>
		          <th>格式</th>
		          <th>开始时间</th>
		          <th>最近执行时间</th>
				  <th>下载</th>
				  <th>操作</th>
		        </tr>
		    </thead>
	        <tbody>
	        <!--  状态(status: ${row[6] }) 类型(scheduleType: ${row[3] }) 格式(filetype: ${row[2] }) 开始时间(startTime: ${row[4] }) 下次执行时间(nextTime: ${row[5] })  
	        <c:forEach items="${pager.data}" var="schedule">
	          <tr>
	            <td></td>
	            <td>${schedule[6] }</td>
	            <td>${schedule[3] }</td>
	            <td>${schedule[2] }</td>
	            <td>${schedule[4] }</td>
	            <td>${schedule[5] }</td>
	            <td>${schedule[0] }</td>
	            <td>${schedule[0] }</td>
	          </tr>
	        </c:forEach>-->
	        </tbody>
	      </table>
	    </div>
	</div>  

	<div id="files">
	  <b></b>
	  <h3>调度生成报表文件</h3>
	  <div>
	    <ul class="info clearfix">
	      <li id="schedule-files-size">
	        <label>文件个数</label>
	        <label class="input" name="size">0个</label>
	      </li>
	      <li id="schedule-files-from">
	        <label>开始时间</label>
	        <label class="input" name="from"><!-- 2016-09-02 --></label>
	      </li>
	      <li id="schedule-files-to">
	        <label>结束时间</label>
	        <label class="input" name="to"><!-- 2016-09-02 --></label>
	      </li>
	    </ul>
	  </div>
	<form id="download-report-form" method="post" action="${base}/report/download" target="_blank" data-validate-type="client"> 
	  <ul>
	    <li class="active input-group">
		  <input type="radio" name="dl-type" value="all" checked="checked"/>
	      <span>下载全部</span>
	    </li>
	    <li class="input-group">
	      <input type="radio" name="dl-type" value="topn" /> 下载最近
	      <input type="number" name="last" id="topn" min="1" disabled="disabled" style="display: table-cell; width: 100px; height: 25px; margin: 0 10px;"/> 个文件
	    </li>
	    <li class="input-group">
	      <input type="radio" name="dl-type" value="range" /> 下载从
	      <span id="scheduling-date"> </span>  间的文件
	      <input type="hidden" name="from" id="scheduling-time-from"/>
	      <input type="hidden" name="to" id="scheduling-time-to"/>
	    </li>
	  </ul>
	  <div class="buttons">
	  	<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" data-form-default-value="${_csrf.token}"/>
	    <input type="hidden" name="scheduleId" id="scheduling-scheduleId"/>
	    <button type="submit" id="btn-download-report-confirm" class="btn btn-danger"><fmt:message key="button.ok" /></button>
	    <button type="reset" id="btn-download-report-cancle" class="btn btn-default" data-dismiss="modal"><fmt:message key="button.cancel" /></button>
	    <span class="error" id="btn-download-report-error"></span>
	  </div>
	</form>
	</div>
	
</div>
<div id="script-container">
<script type="text/javascript">
var reportId = '${reportId}'; // 报表Id
var popconfirm = React.createFactory(antd.Popconfirm);
var rangepicker = React.createFactory(antd.DatePicker.RangePicker);

var statusoptions = {
	"VIRGIN": '<fmt:message key="ui.report.schedule.list.status.virgin" bundle="${i18n_report}" />',
	"SCHEDULED": '<fmt:message key="ui.report.schedule.list.status.scheduled" bundle="${i18n_report}" />',
	"PAUSED": '<fmt:message key="ui.report.schedule.list.status.paused" bundle="${i18n_report}" />',
	"CANCELLED": '<fmt:message key="ui.report.schedule.list.status.cancelled" bundle="${i18n_report}" />',
	"RUNNING": '<fmt:message key="ui.report.schedule.list.status.running" bundle="${i18n_report}" />',
	"FINISHED": '<fmt:message key="ui.report.schedule.list.status.finished" bundle="${i18n_report}" />',
	"WAITING": '<fmt:message key="ui.report.schedule.list.status.waiting" bundle="${i18n_report}" />'
}; 

var ScheduleHandler = {
	table: null,
	selectedIds: [],
	resetBtns: function() {
		if (ScheduleHandler.selectedIds.length == 0) {
			$("#btn-del-scheduling").attr("disabled", true);
		} else {
			$("#btn-del-scheduling").attr("disabled", false);
		}
	},
	_delete: function(ids) {
	    $.ajax({
	    	url: "${base}/report/deletescheduling",
            data: {reportId: reportId, ids: ids},
	        type: "POST",
	        dataType: "json",
	        xhrFields: {
	            errorCodes: '删除报表调度失败'
	        },
	        success: function() {
	        	refresh();
	        }
	    });
	}
};
// 刷新调度数据
function refresh(){
	ScheduleHandler.table.ajax.reload(null, false);
	// 判断全选按钮是否选中，若选中则取消选中状态
	if($("#check-all").is(':checked')) {
    	$("#check-all").click();
	}
}

$(document).ready(function() {
	ReactDOM.render(rangepicker({
		showTime: true,
		style: { width: 184 },
		disabled: true, 
	}), document.getElementById('scheduling-date'));
	
	var table = ScheduleHandler.table = $("#scheduleTable").DataTable({
		columnDefs: [{
            "className": 'select-checkbox',
            "targets": 0
        }, {
            orderable: false, targets: [0, 1, 3, 4, 5, 6]
        }],
        columns: [
			{data: null, width: "15px", defaultContent: ""},
			{data: "6" , render: function(data, type, full, meta){
				return statusoptions[data];
			}},
            {data: "3" },		
			{data: "2" },
			{data: "4" , render: function(data, type, full, meta) {
        		return (new Date(parseInt(data))).format("yyyy-MM-dd hh:mm:ss");   
            }}, 
			{data: "5" , render: function(data, type, full, meta) {
				if(data != null){
					return (new Date(parseInt(data))).format("yyyy-MM-dd hh:mm:ss");	
				}
        		return "";   
            }},
            {data: "0", width:"40px", className:'center', render: function(data, type, full, meta) {
            	return '<a href="javascript:void(0);" data-id="'+data+'" class="btn-download-report" title="下载">'+
            		'<span class="glyphicon glyphicon-download"></span>'+
            	'</a>';
            }},
            {data: "0", orderable: false, defaultContent:"", width:"40px", className:'center'}
		],
		createdRow: function(row, data, dataIndex) {
			var deletepopconfirm = popconfirm({	title:'确定删除报表调度吗？', placement:'topRight', 
					onConfirm:function(e) {
						ScheduleHandler._delete(data[0]);
		    		}
				}, 
				React.createElement('button', {className:'btn btn-xs btn-danger'}, React.createElement('i', {className:'fa fa-trash-o'}))
			);
			ReactDOM.render(deletepopconfirm, $(row).find("td:last-child")[0]);
		},
		order: [],
		processing: true,
        serverSide: true,
        ajax: {
            url: '${base}/report/listscheduling',
            data: function ( d ) {
            	d.reportId = reportId;
                //d.fuzzy = $('#fuzzy').val();
            },
            traditional: false
        },  
        /*scrollY: 300,*/
        paging: false
	}).on('select', function(e, dt, type, indexes) {
        e.stopPropagation();
        if (type === 'row') {
        	ScheduleHandler.selectedIds = ScheduleHandler.selectedIds.concat(table.rows(indexes).data().pluck('0').toArray());
        	ScheduleHandler.resetBtns();
        }
    }).on('deselect', function(e, dt, type, indexes) {
        if (type === 'row') {
            var deselectedIds = table.rows(indexes).data().pluck('o').toArray();
            while (deselectedIds.length > 0) {
                var id = deselectedIds.pop();
                var idx = ScheduleHandler.selectedIds.indexOf(id);
                if (idx > -1)
                	ScheduleHandler.selectedIds.splice(idx, 1);
            }
            ScheduleHandler.resetBtns();
        }
    });

	
	$(document).on("change", "#check-all", function() {//全选和全不选
		ScheduleHandler.selectedIds = [];
		this.checked ? ScheduleHandler.table.rows().select() : ScheduleHandler.table.rows().deselect();
    }).on("click", "#btn-add-scheduling", function() {//新增调度
		window.parent.ReportScheduleHandler.addSchedule(reportId);
	}).on("click", "#btn-search", function() {//搜索调度信息
		//.columns() 搜索文本 	使用正则 	使用智能搜索
		table.search( $("#input-search").val(), false, true ).draw();
	}).on("click", "#btn-refresh", function() {//刷新表格
		//window.location.reload();
		table.ajax.reload(null, false);
	}).on("click", "#btn-del-scheduling", function() {//删除调度
		window.parent.ReportScheduleHandler.delSchedule(reportId, ScheduleHandler.selectedIds);
	}).on("click", ".btn-download-report", function(e){//下载报表文件
		e.stopPropagation();
    	// 报表调度开始时间
    	var report = table.rows($(this).parent()).data()[0];
    	var startTime = parseInt(report["4"]);
		var id = $(this).data("id");
		$("#scheduling-scheduleId").val(id);
		
		$.ajax({
            url: "${base}/report/filesinfo",
            data: {scheduleId: id},
            type: "POST",
            dataType: "json",
            success: function(data) {
            	$("#files").find("label.input").each(function () {
                    var input = $(this);
                    var name = input.attr('name');
                    if(data[name]){
						if(name == "size"){
							var size = parseInt(data[name]);
							$("#topn").attr("max", size);
							input.text(size);
							if(size >　0){
								$("#btn-download-report-confirm").prop("disabled", false);
								$("#btn-download-report-error").text("");
							}else{
								$("#btn-download-report-confirm").prop("disabled", true);
								$("#btn-download-report-error").text("没有文件可供下载！！");
							}
						}else{
							var time = parseInt(data[name]);
                    		var date = new Date(time).format("yyyy-MM-dd");
                    		input.text(date);
						}
                    }else{
                		var date = new Date(startTime).format("yyyy-MM-dd");
                		input.text(date);
					}
                });
            }
        });
		
		var position = $(this).offset();
		position.top += $(this).outerHeight(true);
		position.left -= $("#files").width(); //200;
		$("#files").css(position);
		
		$("#files").slideDown();
		
		$(document).on('click.showing', function(e) {
			if($(e.target).closest('#files').length == 0){
				$("#btn-download-report-cancle").click();
			}
		}.bind(this));
	}).on('click', "#btn-download-report-cancle", function(e) {//取消下载
		// 选中下载所有
		$('#download-report-form').find(':input:radio:first').click();
		$("#files").slideUp();
	}).on('change', "input[type=radio]", function(e) {//选择报表文件
		var value = $(this).val();
		var option = {
	       	showTime: true,
			style: { width: 184 },
			disabled: true, 
			onChange: function(value) {
				console.log(value);
				var from = new Date(value[0]).getTime();
				$("#scheduling-time-from").val(from);
				var to = new Date(value[1]).getTime()+24*3600*1000;
				$("#scheduling-time-to").val(to);
    		},
    		disabledDate:  function(value) {
    			var startDate = $("#schedule-files-from label.input").text();
    			var endDate = $("#schedule-files-to label.input").text();
    		    if (!value || !startDate || !endDate) {
    		        return false;
    		    }
    		    var startTime = new Date(startDate).getTime();
    		    var endTime = new Date(endDate).getTime()+24*3600*1000;
    		    /*只能选中报表开始时间和结束时间范围内的日期*/ 
    		    if(value['time'] <= startTime || value['time'] >= endTime){
    		    	return true;
    		    }else{
    		    	return false; 
    		    }
    		},
    		getCalendarContainer: function(){
    			return document.getElementById('files');
    		}	
		};
		if(value == "range"){
			option.disabled = false;
		}
		if(value == "topn"){
			$("#topn").prop('disabled', false);
		}else{
			$("#topn").prop('disabled', true);
		}
		$('#download-report-form').find('.input-group :input:not(:radio)').val('');
		$('#scheduling-date').empty();
		ReactDOM.render(rangepicker(option), document.getElementById('scheduling-date'));
		$(this).parent().addClass("active").siblings().removeClass("active");
	}).on("click", "#btn-download-report-confirm", function(e){//下载报表
		$("#download-report-form").submit(function(e) {
			$("#btn-download-report-error").text("");// 清空验证信息
			var input = $(this).find('input[name="dl-type"]:checked');
			var value = input.val(), flag = true; 
			if(value != "all"){
				input.siblings("input").each(function(){
				     var obj = $(this).val();
				     if(obj==''){
				    	 flag = false;
				    	 return false;
				     }
				}); 
			}
			if(!flag){
				$("#btn-download-report-error").text("请填写下载条件！！");
			}
			return flag;
		});
	});
});

</script>
</div>
</body>
</html>